<!--
{
单元名称：水印照片测试页面
单元功能：上传图片添加水印
所属模块功能：
创建人：yan
创建时间：230823
修改人：
修改时间：
}
-->
<template>
    <div class="container">
        <m-header :closeFn="onClose">水印照片</m-header>
        <div class="main">
            <div class="info-wrap">
                <div class="title">基本信息</div>
                <div class="content">
                    <div class="cell" v-for="(item,index) in fieldList" :key="index">
                        <m-form
                                ref="formRef"
                                :field="item"
                                @change="onChange"
                                :value="mValue[item.field_id]"
                                :disabled="disabled"
                        ></m-form>
                    </div>
                </div>
            </div>
            <van-uploader
                    v-model:file-list="picList"
                    preview-size="32"
                    :before-read="beforeRead"
            ></van-uploader>
            <img :src="imgSrc" alt="">
        </div>
        <div class="footer">
            <van-button class="btn" color="#24C373" v-show="disabled" plain @click="onEdit">修改乘车人信息</van-button>
            <van-button class="btn" color="#24C373" v-show="!disabled" @click="onSave" v-prevent-re-click>保存乘车人信息</van-button>
        </div>
    </div>

</template>

<script>
  import form from '@/components/form/form'
  import {Uploader, RadioGroup, Radio} from 'vant'
  import {imgCompress,addWatermark,file2Img} from "../../utils/img";
  import {getLocation} from "../../utils/wx";
  import {mapGeocoder} from "../../request/api";
  import {crtTimeFtt} from "../../utils/utils";

  export default {
    name: "watermark",
    components: {
      "m-form": form,
      [Uploader.name]: Uploader,
    },
    data(){
      return {
        // barTitle: '添加乘车人信息',
        fieldList: [
          {
            label: '乘车人姓名',
            type: 'text',
            field_id: 'passengers_name',
            rule: [{required: true}],
          },
          {
            label: '性别',
            type: 'radio',
            defaultValue: '男',
            options: [
              {name: '男',id: '男'},
              {name: '女',id: '女'}
            ],
            field_id: 'sex',
            rule: [{required: true}],
          },
          {
            label: '证件类型',
            type: 'picklist',
            options: [],
            field_id: 'identification_type_name',
            entityKey: 'identification_type_name',
            rule: [{required: true}],
          },
          {
            label: '证件号',
            type: 'text',
            field_id: 'identification_no',
            rule: [{required: true},{validator: (val) => {
                if (this.mValue.identification_type_name !== '身份证') {
                  return true;
                }
                let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
                let _IDre15 =  /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
                // 校验身份证：
                return _IDRe18.test( val ) || _IDre15.test( val )

              }}],

          },
          {
            label: '学校',
            type: 'picklist',
            options: [],
            field_id: 'school_name',
            entityKey: 'school_name',
          },
          {
            label: '年级班级',
            type: 'text',
            placeholder: '请输入例如：六年级一班 输入601',
            field_id: 'class_',
            rule: [
              {required: true},
              {pattern: /^[0-9]{3,4}$/}
            ],
          },
          {
            label: '乘车人照片',
            message: '图片建议正面近照',
            type: 'picture',
            field_id: 'pictures_link',
            rule: [{required: true}],
            picLimit: 1,
            beforeRead: (file) => {
              console.log('读取文件前',file);
              return new Promise(resolve => {
                //文件超出500k压缩
                if (file.size < 512000) resolve(file)
                else imgCompress(file).then(f => resolve(f))
              })
            }
          },
          {
            label: '监护人手机',
            type: 'number',
            field_id: 'guardian_phone',
            rule: [{required: true},{pattern: /^1[3456789]\d{9}$/}],
          },
        ],
        mValue: {},
        disabled: false,
        isEdit: false,
        picList: [],
        imgSrc: ''

      }
    },
    methods: {
      onChange(e){
        let {field,val} = e,
          {field_id} = field;
        let obj = {[field_id]: val};
        if (field.field_id === 'identification_type_name'){
          obj.identification_type_id = val.identification_type_id;
          obj[field_id] = val.identification_type_name;
        }
        if (field.field_id === 'school_name'){
          obj.school_id = val.school_id;
          obj[field_id] = val.school_name;
        }
        if (field.field_id === 'leave_school_name'){
          obj.leave_school_id = val.leave_school_id;
          obj[field_id] = val.leave_school_name;
        }

        this.mValue = {...this.mValue,...obj};

      },
      onEdit(){
        this.disabled = false;
      },
      onClose(){
        this.$emit('close');
      },
      onSave(){
        if (this.validAll()){
          this.$Loading();
          let {customerId,isEdit} = this,
            param = {...this.mValue,customer_id: customerId},
            api;
          if (isEdit) {
            api = editPassenger
          }else {
            api = addPassenger
          }
          api(param).then(res =>{
            if (res.errcode !== 0)return;
            this.$toast.clear();
            this.$emit('close',true);
          })
        }
      },
      validAll(){
        let isValids = [];
        this.$refs.formRef.forEach(item => {
          item.valid(item => isValids.push(item) )
        });
        return !isValids.some(item => !item)
      },


      beforeRead (file){
        console.log('读取文件前',file);
        return new Promise(async resolve => {
          /*//文件超出500k压缩
          if (file.size < 512000) resolve(file)
          else imgCompress(file).then(f => resolve(f))*/
          let local = '佛山市·梁园',
            now = new Date(),
            date = crtTimeFtt(now,'YYYY-MM-DD'),
            time = crtTimeFtt(now,'HH:mm');
          // await this.getLocation().then(name => local = name);
          let opts = [
            {
              content: local,
              font: '24px serif',
              position: {
                bottom: 20,
                left: 30
              }
            },
            {
              content: '粤A66666',
              font: '24px serif',
              position: {
                bottom: 50,
                left: 30
              }
            },
            {
              content: time,
              font: '36px serif',
              position: {
                bottom: 80,
                left: 30
              }
            },
            {
              content: date,
              font: '26px serif',
              position: {
                bottom: 120,
                left: 30
              }
            },
          ]
          imgCompress(file,opts).then(f => resolve(f));
        })
      },
      // afterRead (data) {
      //   file2Img(data.file).then( f => {
      //     this.picList = [{
      //       url: f.src,
      //       isImage: true
      //     }]
      //   })
      // },

      getLocation(){
        return new Promise(resolve => {
          getLocation().then(res => {
            let {latitude,longitude} = res;
            if (!latitude || !longitude)return;
            mapGeocoder({
                "key": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_MAPKEY : window.webConfig.webMapKey,
                "location": `${latitude},${longitude}`,
                "get_poi": "",
                "poi_options": "",
                "output": "",
                "callback": ""
              }).then(res =>{
              let {result} = res,
                {city,district} = result.address_component,
                {recommend} = result.formatted_addresses;
              console.log(city);
              console.log(recommend);
              resolve(`${city}·${recommend}`)
            })
          },err => {
            console.log(err);
            resolve('');
          })
        })
      }
    },
    mounted() {
      // getLocation();
      /*var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
      var location = new TMap.LatLng(39.982915, 116.307015);
      geocoder.getAddress({ location: location }) // 将给定的坐标位置转换为地址
        .then((result) => {
          console.log(result);
          // 显示搜索到的地址
        });*/
      mapGeocoder(
        {
          "key": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_MAPKEY : window.webConfig.webMapKey,
          "location": '23.03586,113.137337',
          "get_poi": "",
          "poi_options": "",
          "output": "",
          "callback": ""
        }).then(res =>{
        let {result} = res,
          {city,district} = result.address_component,
          {recommend} = result.formatted_addresses;
        console.log(city);
        console.log(recommend);
      })

    }
  }
</script>

<style scoped>

</style>
